package edu.sias.common.utils.oss;

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.PutObjectRequest;
import edu.sias.common.config.AliYunOssConfig;
import edu.sias.common.utils.file.FileUploadUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;

@Component
public class AliYunOss {

    private static AliYunOssConfig aliyunOssConfig;

    @Autowired
    public AliYunOss(AliYunOssConfig aliyunOssConfig) {
        AliYunOss.aliyunOssConfig = aliyunOssConfig;
    }

    public static String ossSave(File file) throws OSSException, ClientException {
        DefaultCredentialProvider credentialsProvider = new DefaultCredentialProvider(aliyunOssConfig.getAccessKeyId(), aliyunOssConfig.getAccessKeySecret());
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        OSS ossClient = OSSClientBuilder.create()
                .endpoint(aliyunOssConfig.getEndpoint())
                .credentialsProvider(credentialsProvider)
                .clientConfiguration(clientBuilderConfiguration)
                .region(aliyunOssConfig.getRegion())
                .build();

        String fileName = aliyunOssConfig.getBaseDir() + FileUploadUtils.renameFile(file.getName());
        PutObjectRequest putObjectRequest = new PutObjectRequest(aliyunOssConfig.getBucketName(), fileName, file);
        try {
            ossClient.putObject(putObjectRequest);
        } catch (OSSException | ClientException e) {
            throw e;
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        //返回请求路径
        return "https://"+aliyunOssConfig.getBucketName()+".oss-"+aliyunOssConfig.getRegion()+".aliyuncs.com/"+fileName;
    }
}
